package thread;

import java.lang.management.MemoryUsage;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchornized同步代码锁,多线程同步执行代码,同步监视器
 */
public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop=new Shop();
        Shop shop1=new Shop();
        ReentrantLock r=new ReentrantLock(){
            @Override
            public void lock() {
                super.lock();
            }
        };
        int i=3;
        Thread t1=new Thread("艾瑞莉娅"){
            @Override
            public void run() {

                shop.buy();
            }
        };
        Thread t2=new Thread("魔女杰拉"){
            @Override
            public void run() {
                shop.buy();
            }
        };
        t1.start();
        t2.start();
    }
}
class Shop{
     void  buy(){
        try {
            Thread t=Thread.currentThread();
            System.out.println(t.getName()+":正在挑衣服");
            Thread.sleep(1000);
//            synchronized( this){//这里使用this,那么调用buy方法时候需要指定同一个对象,不然无法互斥
//                System.out.println(t.getName()+":正在试衣服");
//                Thread.sleep(5000);
//                System.out.println(t.getName()+":试完出来了");
//            }
//            synchronized( MemoryUsage.class){
//                System.out.println(t.getName()+":正在试衣服");
//                Thread.sleep(5000);
//                System.out.println(t.getName()+":试完出来了");
//            }



               synchronized (Shop.class){//指定Shop.class,调用buy方法时候,传入不同对象,也会互斥,因为shop.class是唯一的
                    System.out.println(t.getName()+":正在试衣服");
                    Thread.sleep(5000);
                    System.out.println(t.getName()+":试完出来了");
                }

            System.out.println(t.getName()+":结账");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
